package com.soccertgc.core.game.requests
{	
	import com.soccertgc.core.Position;
	
	
	public class GameRequestSubstituteParams extends GameRequestParams
	{
		
		// -------------------------------------------------------------------------------
		// CONSTANTS
		// -------------------------------------------------------------------------------
		
		// Max discard
		public static const			MAX_DISCARD_POSITIONS:int				= 2;
		
		// JSON properties names
		protected static const		JSON_PROPERTY_SUBSTITUTIONS:String		= "substitutions";		
		
		// -------------------------------------------------------------------------------
		// FIELDS
		// -------------------------------------------------------------------------------
		
		private var _positions:Vector.<Position>;
		
		// -------------------------------------------------------------------------------
		// CONSTRUCTOR
		// -------------------------------------------------------------------------------
		
		public function GameRequestSubstituteParams()
		{
			super();
		}
		
		// -------------------------------------------------------------------------------
		// PROPERTIES
		// -------------------------------------------------------------------------------
		
		// -------------------------------------------------------------------------------
		// PRIVATE METHODS
		// -------------------------------------------------------------------------------
		
		protected function getPositionIndex(position:Position):int
		{
			for (var i:int = 0; i < _positions.length; i++)
			{
				if (_positions[i] = position) return i;
			}
			return -1;
		}
		
		
		override protected function createActionData():Object
		{
			// Encode all played cards to JSON
			var cards:Array = new Array();
			for (var i:int = 0; i < _positions.length; i++)
			{
				cards.push(_positions[i].sign);
			}
			// Encode base data to JSON
			var json:Object = new Object();
			json[JSON_PROPERTY_SUBSTITUTIONS] = cards;
			// Encoded
			return json;
		}
		
		// -------------------------------------------------------------------------------
		// PUBLIC METHODS
		// -------------------------------------------------------------------------------
		
		/**
		 * 
		 * @param card
		 * @param target
		 */		
		public function add(position:Position):void
		{
			if (_positions.length < MAX_DISCARD_POSITIONS) throw new Error("Max number of substitutions (" + MAX_DISCARD_POSITIONS + ") already defined");
			_positions.push(position);
		}
		
		/**
		 * 
		 * @param card
		 * 
		 */		
		public function remove(position:Position):void
		{
			var i:int = getPositionIndex(position);
			_positions.splice(i, 1);
		}
		
		/**
		 * 
		 */		
		override public function clear():void
		{
			_positions.splice(0, _positions.length);
		}
		
	}
	
}